<template>
<div class="resultwrap">
    <div class="maincontent">
      <van-overlay :show="showSaveImage" @click="showSaveImage = false" :lock-scroll="false" :z-index="9999">
        <div class="wrapper" @click.stop="showSaveImage = false">
          <p class="savetext">长按图片保存到手机相册↓↓↓</p>
          <img :src="saveImage" alt="" style="width: 100%">
        </div>
      </van-overlay>
      
      <div class="babyinfo">
          <div class="resulttop">
              <h2 class="h2">测评结果</h2>
              <p class="p1">您的得分为：</p>
              <div class="scoreview">
                  <span class="s1">{{result.total_score}}</span>
                  <span class="s2">分</span>
              </div>
              <div class="resuttips" v-if="result.is_unusual == true" v-html="result.warning_text"></div>
          </div>
          <charts v-if="!loading" :width="'100%'" :height="'5.2rem'" :category="categoryData" :series="seriesData" :seriesResult="seriesDataResult"></charts>
          <p class="fenxih3"><span class="ss">评测分析</span></p>
          <div :class="{'analyseview': true, 'abnormal': item.result == '异常'}" v-for="(item, index) in result.data" :key="index">
              <div class="analysetop">
                  <p class="pleft">{{item.title}}</p>
                  <p class="pright">得分： <span class="sum">{{item.score}}</span></p>
              </div>
              <div class="analyseitem">
                  <p class="itemtips">{{item.tips}}</p>
                  <div class="textview" v-html="item.desc"></div>
                  <!-- <p class="itemretips">
                    <span class="zticon normalicon" v-if="item.result == '正常'"></span>
                    <span class="zticon abnormalicon" v-else></span>
                  </p> -->
                  <div class="itemretips nor" v-if="item.result == '正常'">
                    <span class="zticon normalicon"></span>
                    <p class="rrt">测评结果：正常</p>
                  </div>
                  <div class="itemretips abnor" v-else>
                      <span class="zticon abnormalicon"></span>
                      <p class="rrt">测评结果：异常</p>
                  </div>
                  <div class="resulttext normal" v-html="item.result_desc"></div>
              </div>
          </div>
      </div>
    </div>
    <van-button type="primary" class="saveresult" @click="saveAsImage" size="small">保存结果</van-button>
</div>
</template>

<script setup>
import api from "../api";
import { showLoadingToast, closeToast, showFailToast, showImagePreview } from "vant";
import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';
import charts from "../components/Charts.vue";
import { computed, ref } from "vue";

const route = useRoute();
const router = useRouter();
const infoStore = useInfoStore();
const loading = ref(true)
const result = ref({})
const saveImage = ref('')
const showSaveImage = ref(false)
const getResult = () => {
  api
    .getResult({
      user_id: infoStore.userId
    })
    .then((res) => {
      if (res.code === 200) {
        result.value = res.data;
        setTimeout(() => {
          loading.value = false
        }, 800)
        closeToast();
      } else {
        showFailToast({
          message: res.message,
          duration: 0,
        });
        return false;
      }
    })
    .finally((_) => {
      
    });
}

const categoryData = computed(() => {
  let data = []
  const resultData = result.value.data
  if(resultData) {
    resultData.forEach(element => {
      data.push(element.title)
    });
  }
  
  return data
})

const seriesData = computed(() => {
  let data = []
  const resultData = result.value.data
  if(resultData) {
    resultData.forEach(element => {
      data.push(element.score)
    });
  }
  return data
})

const seriesDataResult = computed(() => {
  let data = []
  const resultData = result.value.data
  if(resultData) {
    resultData.forEach(element => {
      data.push(element.result)
    });
  }
  return data
})

const saveAsImage = () => {
  const element = document.querySelector('.maincontent');
  html2canvas(element).then((canvas) => {
    const imageDataUrl = canvas.toDataURL('image/png'); // 将Canvas对象转换为Base64编码的图像数据URL
    
    saveImage.value = imageDataUrl
    showSaveImage.value = true

    

    console.log(imageDataUrl); // 输出图像数据URL到控制台

    // 将base64数据转换为Blob对象
    // const blob = base64ToBlob(imageDataUrl);

    // 使用FileSaver的saveAs方法保存文件
    // saveAs(blob, infoStore.info.name+'测评结果.png');
  });
}

const base64ToBlob = (base64Data) => {
  const contentType = base64Data.split(';')[0].split(':')[1];
  const raw = window.atob(base64Data.split(',')[1]);
  const rawLength = raw.length;
  const uInt8Array = new Uint8Array(rawLength);

  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  return new Blob([uInt8Array], { type: contentType });
}

onMounted(() => {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    loadingType: "spinner",
    duration: 0,
  });

  getResult()
});
</script>
<style>
.wrapper {
  margin: 0.2rem;
  min-height: 1rem;
  height: 100%;
  padding-bottom: 0.3rem;
  overflow-y: auto;
}
.savetext {
  text-align: center;
    width: 100%;
    padding: 0.2rem;
    font-size: 0.4rem;
    background-color: white;
    color: red;
}
</style>